package com.fzebu.fastboot.form.converter;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fzebu.fastboot.form.TypeUtil;
import com.fzebu.fastboot.form.exception.ConvertException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author Jack
 * @version 1.0.0
 * @create 2020/1/26 20:58
 */
@Slf4j(topic = "debug")
public abstract class AbstractProcessHandler implements ProcessHandler {

    protected FormConverter.Builder builder;

    @Override
    public void initialize(FormConverter.Builder builder) {
        this.builder = builder;
    }

    protected Object toJavaBean(JSONObject json) throws ConvertException {
        try {
            return json.toJavaObject(builder.getClazz());
        } catch (JSONException e) {
            log.error("form convert fail, msg: {}", e.getMessage());
            throw new ConvertException(e.getMessage());
        }
    }

    protected int putValue(JSONObject json, String name, String val) {
        List<String> l = this.builder.getAliasFieldMap().get(name);
        int result = 0;
        if (l == null) return result;
        for (String k : l) {
            Object obj = TypeUtil.doParse(builder.getFieldMap().get(k), k, val);
            json.put(k, obj);
            result = 1;
        }
        return result;
    }
}
